
const config = require('../config/config.js')
const monk = require('monk')

const url = `${config.mongodb.host}:${config.mongodb.port}/${config.mongodb.dbname}`
const option = {
    reconnectTries: 3,
    autoReconnect: true,
    poolSize : 40,
    connectTimeoutMS: 500
}
const db = monk(url, option)

/*exports.db = () => {
    console.log(`${config.mongodb.host}:${config.mongodb.port}/${config.mongodb.dbname}`)
    return new Promise((resolve, reject) => {
        
        const db = monk(`${config.mongodb.host}:${config.mongodb.port}/${config.mongodb.dbname}`)
    })
}*/
exports.table = (table) => {
    return new Promise((resolve, reject) => {
        if(db._state == 'closed') return reject('MongoDB is closed!')
        resolve(db.get(table))
    })
}
exports.findAll = async (table, condition) => {
    let tbl = await this.table(table)
    return tbl.find(condition)
}
exports.findLimit = async (table, condition, page=1, pagesize=20) => {
    let tbl = await this.table(table)
    return tbl.find( condition, {"limit":pagesize,"skip":(page-1)*pagesize} )
}
exports.findLimitCount = async (table, condition) => {
    let tbl = await this.table(table)
    return tbl.count( condition )
}

exports.insert = async (table, obj) => {
    let tbl = await this.table(table)
    return tbl.insert(obj)
}
exports.update = async (table, obj, condition, insert_new=false ) => {
    let tbl = await this.table(table)
    return tbl.update(condition, obj, insert_new)
}
exports.remove = async (table, condition) => {
    let tbl = await this.table(table)
    return tbl.remove(condition)
}